﻿using Microsoft.Extensions.Options;
using System;

namespace Fast
{
    public class FastDefaultJsonSerializer : IJsonSerializer
    {
        protected FastJsonOptions Options { get; }
        public IJsonSerializerProvider SerializerProvider { get; }
        public FastDefaultJsonSerializer(IOptions<FastJsonOptions> options, IJsonSerializerProvider serializerProvider)
        {
            Check.NotNull(options.Value, nameof(options));
            Check.NotNull(serializerProvider, nameof(serializerProvider));

            Options = options.Value;
            SerializerProvider = serializerProvider;
        }

        /// <summary>
        /// 序列化成 Json 字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="camelCase">是否采用驼峰命名法</param>
        /// <param name="indented">是否缩进</param>
        /// <returns></returns>
        public string Serialize(object obj, bool camelCase = true, bool indented = false)
        {
            Check.NotNull(obj, nameof(obj));

            return SerializerProvider.Serialize(obj, camelCase, indented);
        }

        /// <summary>
        /// 反序列化成指定类型对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString">目标Json字符串</param>
        /// <param name="camelCase">是否采用驼峰命名法</param>
        /// <returns></returns>
        public T Deserialize<T>(string jsonString, bool camelCase = true)
        {
            Check.NotNull(jsonString, nameof(jsonString));

            return SerializerProvider.Deserialize<T>(jsonString, camelCase);
        }

        /// <summary>
        /// 反序列化成 <see cref="Type"/> 类型的 <see cref="object"/> 对象。得到结果后可以显示转换为 <see cref="Type"/> 类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="jsonString">目标Json字符串</param>
        /// <param name="camelCase">是否采用驼峰命名法</param>
        /// <returns></returns>
        public object Deserialize(Type type, string jsonString, bool camelCase = true)
        {
            Check.NotNull(type, nameof(type));
            Check.NotNull(jsonString, nameof(jsonString));

            return SerializerProvider.Deserialize(type, jsonString, camelCase);
        }
    }
}
